/**  
 * All rights Reserved, Designed By Android_Robot   
 * @Title:  OverSurfaceView.java   
 * @Package com.jiyi.widget   
 * @Description:    TODO(用一句话描述该文件做什么)   
 * @author: HYM     
 * @date:   2017-9-12 上午11:02:04   
 * @version V1.0     
 */
package com.jiyi.widget;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.PointF;
import android.util.AttributeSet;
import android.util.Log;
import android.view.MotionEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.ViewGroup;

import com.jiyi.bean.owner.PositionPoint;
import com.swift.maintenance.R;

import java.util.ArrayList;

/**
 * Created by Administrator on 2016/5/20.
 */
public class OverSurfaceView extends SurfaceView implements
		SurfaceHolder.Callback {
	private static final String TAG = "测试";
	private Canvas canvas = null; // 定义画布
	private SurfaceHolder sfh = null;
	// 不支持下面两种模式
	private static final int NONE = 0;
	private static final int CLICK = 3;// 单点模式
	/** 拖拉照片模式 */
	private static final int DRAG = 1;
	// 放大缩小模式
	private static final int ZOOM = 2;
	// 初始化为空模式
	private int mode = NONE;
	private PointF start = new PointF();
	private PointF mid = new PointF();
	/** 最后一次触摸时的位置 */
	private PointF end = new PointF();
	/** 地图中心位置中心 */
	private PointF screenCenter = new PointF();
	/** 图纸宽高 */
	private PointF mapCenter = new PointF();
	private Bitmap bm;// 加载的地图
	/** 标注点 */
	// 缩放倍率
	private float rate = 1f;
	// 图片缩放前后连个手指间的距离
	private float oldDist = 1f;
	private float newDist;
	private float oldRate = 1;
	private Bitmap b;// 标注物
	// 控件宽高
	private int h;
	private Matrix matrix;
	private int w;
	// 图片长宽
	private int mapH;
	private int mapW;
	private float scaleH;// 原始高缩放比例
	private float scaleW;// 原始宽缩放比例
	private ArrayList<PositionPoint> positionPoints;// 装标注点信息的点
	ViewGroup parentView;

	public OverSurfaceView(Context context) {
		super(context);
		start();
	}// ，没有自定义属性，不需要再xml中使用所以只重载这个构造方法

	public OverSurfaceView(Context context, AttributeSet attrs) {
		super(context, attrs);// 在xml中使用就要定义这个构造方法
		start();
	}

	@Override
	public void surfaceCreated(SurfaceHolder holder) {
		if (bm == null) {
			bm = BitmapFactory.decodeResource(getResources(),
					R.mipmap.maintenace);
		}
		mapH = bm.getHeight();
		mapW = bm.getWidth();
		h = getHeight();
		w = getWidth();
		screenCenter.set(w / 2, h / 2);
		mapCenter.set(mapW / 2, mapH / 2);// 记录地图中心位置
		calculateScale();
		draw();
	}

	@Override
	public void surfaceChanged(SurfaceHolder holder, int format, int width,
			int height) {

	}

	@Override
	public void surfaceDestroyed(SurfaceHolder holder) {

	}

	private void draw() {
		canvas = sfh.lockCanvas();
		Paint paint = new Paint();
		matrix = new Matrix();

		matrix.setScale(rate, rate, mapCenter.x, mapCenter.y);
		matrix.postTranslate(screenCenter.x + (end.x - start.x) - mapCenter.x,
				screenCenter.y + (end.y - start.y) - mapCenter.y);

		Log.e("rate1", "" + rate + "," + bm.getHeight() + "," + bm.getWidth()
				+ "," + screenCenter.x + "," + mapCenter.x * rate);
		canvas.drawColor(Color.WHITE);
		canvas.drawBitmap(bm, matrix, paint);
		/* //**背景颜色 *//*
        *//** 标注坐标 */
		/*
        *//** 画标注点 */
		b = BitmapFactory
				.decodeResource(getResources(), R.drawable.icon_add_on);
		Matrix matrix = new Matrix();
		for (int i = 0; i < positionPoints.size(); i++) {
			matrix.setScale(1, 1, b.getWidth() / 2, b.getHeight() / 2);
			matrix.postTranslate(
					screenCenter.x + (end.x - start.x) - bm.getWidth() * rate
							/ 2 - b.getWidth() / 2
							+ positionPoints.get(i).getPointX() * rate,
					screenCenter.y + (end.y - start.y) - bm.getHeight() * rate
							/ 2 - b.getHeight() / 2
							+ positionPoints.get(i).getPointY() * rate);
			canvas.drawBitmap(b, matrix, new Paint());
			Log.e("测试",
					screenCenter.x + "x" + b.getWidth() / 2 + "b"
							+ bm.getWidth() / 2 + "bm"
							+ positionPoints.get(i).getPointX() * rate
							+ "pooint");
			Log.e("测试1", screenCenter.x + (end.x - start.x) - bm.getWidth()
					* rate / 2 - b.getWidth() / 2
					+ positionPoints.get(i).getPointX() * rate + "点击的x"
					+ start.x);
		}
		sfh.unlockCanvasAndPost(canvas);
	}

	public void calculateScale() {
		scaleW = (float) w / mapW;
		scaleH = (float) h / mapH;
		if (scaleW < scaleH) {
			rate = scaleW;
		} else {
			rate = scaleH;
		}
	}

	@Override
	public boolean onTouchEvent(MotionEvent event) {
		switch (event.getAction() & MotionEvent.ACTION_MASK) {
		case MotionEvent.ACTION_DOWN:
			if (parentView !=null) {
				parentView.requestDisallowInterceptTouchEvent(true);
			}
			float startX = event.getX();
			float startY = event.getY();
			start.set(startX, startY);// 记录开始的位置
			end.set(startX, startY);
			mode = CLICK;// 单点模式
			Log.e(TAG, "start------------------------" + event.getX() + "----"
					+ event.getY());
			break;

		case MotionEvent.ACTION_POINTER_DOWN:// 多点触摸
			oldDist = spacing(event);// 按下时两个手指间的距离
			Log.d(TAG, "oldDist" + "-----------------oldDist----------");
			Log.d(TAG, "oldDist=" + oldDist);
			if (oldDist > 10f) {
				screenCenter.x = getWidth() / 2;
				screenCenter.y = getHeight() / 2;
				midPoint(mid, event);
				mode = ZOOM;
			}
			break;
		case MotionEvent.ACTION_UP:
			if (parentView !=null) {
				parentView.requestDisallowInterceptTouchEvent(false);
			}
			boolean flag = whichItemImage(start.x, start.y);
			oldRate = rate;
			float x = (float) Math.sqrt((event.getX() - start.x)
					* (event.getX() - start.x) + (event.getY() - start.y)
					* (event.getY() - start.y));
			if (x < 10 && mode == CLICK && flag) {
				PositionPoint positionPoint = new PositionPoint();// 这个点是相对于图片坐标的点
				positionPoint.setPointX((start.x - (screenCenter.x - bm
						.getWidth() * rate / 2))
						/ rate);
				positionPoint.setPointY((start.y - (screenCenter.y - bm
						.getHeight() * rate / 2))
						/ rate);
				positionPoints.add(positionPoint);
				end.set(start.x, start.y);
//				Log.e("x比例   ", (event.getX()-(-mapCenter.x * rate)/(mapCenter.x *2 * rate))+"");
				draw();
			} else if (mode == CLICK) {
				screenCenter.set(screenCenter.x + (end.x - start.x),
						screenCenter.y + (end.y - start.y));
			}
			// 记录移动后地图中心位置(坐标点在屏幕的中心)
			Log.d(TAG, "end------------------------" + event.getX() + "----"
					+ event.getY());
			break;
		case MotionEvent.ACTION_POINTER_UP:
			mode = NONE;
			break;
		case MotionEvent.ACTION_MOVE:
			x = (float) Math.sqrt((event.getX() - start.x)
					* (event.getX() - start.x) + (event.getY() - start.y)
					* (event.getY() - start.y));
			if (mode == CLICK && x > 10) {// 设置最后一个点的位置
//				if (screenCenter.x + (event.getX() - start.x) < mapCenter.x
//						* rate) {
					end.set(event.getX(), event.getY());
					draw();
//				}
				// }
				Log.d("移动测试", "end----" + screenCenter.x
						+ (event.getX() - start.x) + "------.ACTION_MOVE----"
						+ mapCenter.x * rate + "----------" + event.getX()
						+ "----" + event.getY());

			} else if (mode == ZOOM) {
				newDist = spacing(event);// 移动后两个手指间的距离
				if (newDist > 10f
						&& ((newDist - oldDist) > 10 || (newDist - oldDist) < -10)) {
					rate = oldRate * (newDist / oldDist);// 设置缩放比例
					draw();
				}
			}

			break;
		}
		return true;
	}

	/**
	 * 对所画点的判断，因为图片比较小，所以在坐标点上X、Y点分别加减20dp像素，也就是在正常的情况下图片的点击区域是一个边长为40dp的正方形，
	 * 因为涉及到缩放，需要乘以Scale（缩放比例）所以点击区域大小也是变的
	 */
	public boolean whichItemImage(float x, float y) {
		boolean flag = true;

		for (int i = 0; i < positionPoints.size(); i++) {
			float x1 = screenCenter.x + (end.x - start.x) - bm.getWidth()
					* rate / 2 + positionPoints.get(i).getPointX() * rate + b.getWidth() / 2;
			float x2 = screenCenter.x + (end.x - start.x) - bm.getWidth()
					* rate / 2 + positionPoints.get(i).getPointX() * rate -b.getWidth() / 2;
			float y1 = screenCenter.y + (end.y - start.y) - bm.getHeight()
					* rate / 2 + positionPoints.get(i).getPointY() * rate + b.getWidth() / 2;
			float y2 = screenCenter.y + (end.y - start.y) - bm.getHeight()
					* rate / 2 + positionPoints.get(i).getPointY() * rate - b.getWidth() / 2;
			Log.d(TAG, "x1========" + x1);
			Log.d(TAG, "x2========" + x2);
			Log.d(TAG, "y1========" + y1);
			Log.d(TAG, "y2========" + y2);
			if (x <= x1 && x >= x2 && y <= y1 && y >= y2) {
				Log.e("你点击了哪个按钮", "" + i);
				flag = false;
			}
		}
		return flag;
	}

	private float spacing(MotionEvent event) {
		float x = event.getX(0) - event.getX(1);
		float y = event.getY(0) - event.getY(1);
		return (float) Math.sqrt(x * x + y * y);
	}

	// 求重点坐标
	private void midPoint(PointF point, MotionEvent event) {
		float x = event.getX(0) + event.getX(1);
		float y = event.getY(0) + event.getY(1);
		point.set(x / 2, y / 2);
	}

	public ViewGroup getParentView() {
		return parentView;
	}

	public void setParentView(ViewGroup parentView) {
		this.parentView = parentView;
	}
	
	void start()
	{
		sfh = getHolder();
		sfh.addCallback(this);
		if (null == positionPoints) {
			positionPoints = new ArrayList<PositionPoint>();
		}
	}

	public Bitmap getBm() {
		return bm;
	}

	public void setBm(Bitmap bm) {
		this.bm = bm;
	}

	public Bitmap getB() {
		return b;
	}

	public void setB(Bitmap b) {
		this.b = b;
	}

	public ArrayList<PositionPoint> getPositionPoints() {
		return positionPoints;
	}

	public void setPositionPoints(ArrayList<PositionPoint> positionPoints) {
		this.positionPoints = positionPoints;
	}
	
	
	
}
